#!/usr/bin/env bash

if [ $# -ne 2 ]; then
    echo "Usage: $0 patternTrials"
    exit 1
fi

trap 'kill -INT -$pid; exit 1' INT

pattern=$1
runs=$2

cd "/home/huth/go/6.824/src/raft" || cd "/home/huth/go/mit6.824/src/raft" || cd "/Users/huth/Developer/go/6.824/src/raft" || exit 1
logPath=../../logs/raft
FILE_PREFIX="$logPath"/test-many-$(date '+%m-%d_%H:%M:%S')

if [ "$(uname -s)" == "Linux" ]; then
  export GOROOT="/usr/lib/go"
  export GOBIN=$GOROOT/bin
  export GOPATH="/home/huth/go"
  export PATH=$PATH:$GOROOT/bin
  export GO111MODULE=on
  export GOPROXY=https://goproxy.cn
  source ~/.profile
fi

#go build -race && echo BUILD OK!
OUTFILE=$FILE_PREFIX"_0.log"
echo "" > $OUTFILE
for i in $(seq 1 $runs); do
    NEWFILE=$FILE_PREFIX"_"$i".log"
    mv $OUTFILE $NEWFILE
    OUTFILE=$NEWFILE
    echo Trying the "$i"th ...
    go clean && go test -run $pattern -race 1>"$OUTFILE" 2>"$OUTFILE"
    grepRes=`grep -w -E "RACE|FAIL" "$OUTFILE"`
    if [ ! -z "$grepRes" ]; then
        echo FAILED when try the "$i"th time:
        echo "$grepRes"
        exit 1
    fi
#    pid=$!
#    if ! wait $pid; then
#        echo '***' FAILED TESTS IN TRIAL $i >> $OUTFILE
#        exit 1
#    fi
    echo the "$i"th time is PASSED
done
mv $OUTFILE $FILE_PREFIX"_PASS.log"
echo '***' PASSED ALL TEST of $pattern > $FILE_PREFIX"_PASS.log"